#include "helperController.h"
#include "view/helperView.h"
#include "view/camera/ortho_camera.h"

HelperController::HelperController(View* view,Model* model)
	:	SceneController(view,model){
}

HelperController::~HelperController(){

}

void HelperController::mouseMotion(float x ,float y){
	HelperView& pview = dynamic_cast<HelperView&>(*this->view);
	if(mapDrag){
		OrthoCamera& camera = dynamic_cast<OrthoCamera&>(pview.getCamera());
		Point center = camera.getEye();
		Point dragAmount = mapDragPos-Point(x,y);
		dragAmount.x2 *= -1;

		camera.updatePosition(center+dragAmount,Point(0,0,-1),NULL);
		mapDragPos = Point(x,y);
	}
}

void HelperController::mousePressed(int key,int state,float x ,float y){
	if(key==GLUT_MIDDLE_BUTTON && state==GLUT_DOWN){
		mapDrag=true;
		mapDragPos = Point(x,y);
	}

	if(key==GLUT_MIDDLE_BUTTON && state==GLUT_UP)
		mapDrag=false;

	if(key==GLUT_RIGHT_BUTTON && state==GLUT_DOWN){
		addControlPoint(x,y);
	}
}

void HelperController::addControlPoint(float x,float y){
	HelperView& sview = dynamic_cast<HelperView&>(*view);
	OrthoCamera& camera = dynamic_cast<OrthoCamera&>(sview.getCamera());
	SceneModel& smodel = dynamic_cast<SceneModel&>(*model);

	x = (x/sview.getViewport().width()*camera.getViewVolume().width()) - camera.getViewVolume().width()*0.5f;
	y = ((sview.getViewport().height()-y)/sview.getViewport().height()*camera.getViewVolume().depth()) - camera.getViewVolume().depth()*0.5f;

	Point wpos = Point(camera.getEye().x1,camera.getEye().x2,1.2f)+Point(x,y);

	/* Para poder capturar posiciones */
	std::fstream out("dist.data");
	if(!out.is_open())
		out.open("dist.data",std::fstream::out | std::fstream::trunc);
	out.seekp(0,std::fstream::end);
	std::ostringstream oss;
	oss << wpos.x1 << "," << wpos.x2 << "," << smodel.getGround().calculateZ(wpos.x1,wpos.x2) << std::endl;

	out.write(oss.str().c_str(),oss.str().size());
	sview.spline.addPoint(Point(wpos.x1,wpos.x2,2.0f));

	out.close();
}

void HelperController::keyboard(unsigned char key,float x,float y){
	SceneController::keyboard(key,x,y);

	HelperView& sview = dynamic_cast<HelperView&>(*view);
	SceneModel& smodel = dynamic_cast<SceneModel&>(*model);
	switch(key){
		case 'x':
			// dump curve points
			std::fstream out("dump.data");
			if(!out.is_open())
				out.open("dump.data",std::fstream::out | std::fstream::trunc);
			out.seekp(0,std::fstream::end);
			sview.spline.calculatePoints();
			CurveModel::Points::const_iterator it = sview.spline.pointsBegin();
			for(;it!=sview.spline.pointsEnd();++it){
				Point wpos = *it;
				std::ostringstream oss;
				oss << wpos.x1 << "," << wpos.x2 << "," << smodel.getGround().calculateZ(wpos.x1,wpos.x2)+wpos.x3 << std::endl;
				out.write(oss.str().c_str(),oss.str().size());
			}
			out.close();
			break;
	}
}
